<template>
	<div style="width: 90%">
		<el-upload ref="uploadRef" :action="props.url" :data="params" :class="{ 'disabled-upload': fileList.length == limit }" :file-list="showFileList" :headers="{ Authorization: getCurToken() }" :limit="limit" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleSuccess">
			<div class="flex">
				<el-icon style="display: block">
					<ele-Plus />
				</el-icon>
				<span class="text">图片</span>
			</div>
		</el-upload>

		<el-dialog v-model="dialogVisible" title="图片预览">
			<el-image fit="cover" :src="dialogImageUrl" />
		</el-dialog>
	</div>
</template>
<script setup>
import global from '@/utils/global'
import { getToken } from '@/utils/storage'
const props = defineProps({
	modelValue: {
		type: [Array, String],
		default: () => [],
	},
	url: {
		type: String,
		default: import.meta.env.VITE_API_URL + '/meta-system/web/v1/upload/uploadByBucketName',
	},
	limit: {
		// 限制上传数量
		type: Number,
		default: 100,
	},
	params: {
		type: Object,
		default: () => {},
	},
	previewUrl: {
		type: String,
		default: import.meta.env.VITE_IMAGE_PREVIEW,
	},
})
const emit = defineEmits(['update:modelValue'])

watch(
	() => props.modelValue,
	value => {
		if (props.limit == 1) {
			if (value) {
				// 数据
				fileList.value = [
					{
						url: value,
					},
				]
				// 显示
				showFileList.value = [
					{
						url: props.previewUrl + value,
					},
				]
			} else {
				fileList.value = []
				showFileList.value = []
			}
		} else {
			if (value.length > 0) {
				fileList.value = value
				showFileList.value = value.map(item => ({
					url: props.previewUrl + item.url,
				}))
			} else {
				fileList.value = []
				showFileList.value = []
			}
		}
	}
)
const fileList = ref([])
const showFileList = ref([])

const uploadRef = ref(null)
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove = uploadFile => {
	if (props.limit == 1) {
		fileList.value = []
		showFileList.value = []
	} else {
		let deleteUrl = ''
		if (uploadFile.response) {
			const urlAry = uploadFile.response.data.url.split('/')
			deleteUrl = urlAry[urlAry.length - 1]
		} else {
			const urlAry = uploadFile.url
			deleteUrl = urlAry[urlAry.length - 1]
		}
		const arrayList = [...fileList.value]
		fileList.value.splice(
			arrayList.findIndex((item, index) => {
				const fileAry = item.url.split('/')
				if (fileAry[fileAry.length - 1] == deleteUrl) {
					return index
				}
			}),
			1
		)
		showFileList.value = fileList.value.map(item => ({
			url: global.$previewUrl + item.url,
		}))
	}
	successAction()
}
const handleSuccess = (response, uploadFile) => {
	if (response.code == 200) {
		// 数据
		fileList.value.push({
			name: response.data.fileName,
			url: `${response.data.bucketName}/${response.data.url}`,
		})
		// 回显
		showFileList.value.push({
			url: `${props.previewUrl}${response.data.bucketName}/${response.data.url}`,
		})
		successAction()
	} else {
		global.$baseMessage('上传失败！', 'error')
		// state.uploadRef.clearFiles()
		uploadRef.value.handleRemove(uploadFile)
	}
}
const successAction = () => {
	if (props.limit == 1) {
		if (fileList.value.length > 0) {
			emit('update:modelValue', fileList.value[0].url)
		} else {
			emit('update:modelValue', '')
		}
	} else {
		emit('update:modelValue', fileList.value)
	}
}
const handlePictureCardPreview = uploadFile => {
	console.log(uploadFile.url)
	dialogImageUrl.value = uploadFile.url
	dialogVisible.value = true
}
const getCurToken = () => {
	const tokenVal = getToken()
	return `sop ${tokenVal}`
}
const handleResetValue = () => {
	fileList.value = []
	showFileList.value = []
}

defineExpose({
	handleResetValue,
})
</script>
<style lang="scss" scoped>
.disabled-upload {
	:deep() {
		.el-upload--picture-card {
			display: none;
		}
	}
}
:deep() {
	.el-upload--picture-card {
		width: 90% !important;
		min-width: 148px;
	}
	.el-upload-list__item {
		transition: none !important;
	}
}

.el-image-viewer__close {
	top: 80px !important;
}
.el-image {
	width: 100% !important;
}
.flex {
	display: flex;
	flex-direction: column;
	align-items: center;
}
.text {
	margin-top: 3px;
	font-size: 12px;
	letter-spacing: 1px;
}
</style>
